#!/usr/bin/ruby

require 'osx/cocoa'
include OSX

dirs = Dir.glob(NSHomeDirectory() + "/Library/Application Support/MobileSync/Backup/*")
backup_dir = dirs[0] if dirs.size

def plist_for_path(path)
  thisData = NSData.dataWithContentsOfFile_(path)
	thisPlist = NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_(
		thisData, NSPropertyListImmutable, nil, nil)
  return thisPlist
end

def make_dir_for_plist(plist)
  domain = plist.objectForKey_('Domain')
	path = plist.objectForKey_('Path')
	%x{mkdir -p "extract/#{domain}/#{File.dirname(path)}"}
end


Dir.glob(backup_dir + "/*.mdbackup") do |testPath|
  plist = plist_for_path(testPath)
  make_dir_for_plist(plist)
	domain = plist.objectForKey_('Domain')
	path = plist.objectForKey_('Path')
	data = plist.objectForKey_('Data')
	puts "Extracting #{domain}/#{path}"
  data.writeToFile_atomically_("extract/#{domain}/#{path}", true)
end

Dir.glob(backup_dir + "/*.mdinfo") do |testPath|
  plist = plist_for_path(testPath)
  make_dir_for_plist(plist)
  domain = plist.objectForKey_('Domain')
	path = plist.objectForKey_('Path')
  data_path = testPath.sub(/.mdinfo$/,'.mddata')
  data = NSData.dataWithContentsOfFile(data_path)
  puts "Extracting #{domain}/#{path}"
  data.writeToFile_atomically_("extract/#{domain}/#{path}", true)
end